package htmlbrowser.domtree;

import java.awt.Container;
import java.awt.GridLayout;
import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

public class HTMLDOMTreeFrame extends JFrame 
		implements TreeSelectionListener {
	private AttributesTableModel attrModel = new AttributesTableModel();
	private JTree domTree = new JTree();
	public DefaultTreeModel domTreeModel = (DefaultTreeModel) domTree.getModel();
	private JTable attrTable = new JTable(attrModel);
	
	public HTMLDOMTreeFrame() {
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		initComponents();
		pack();
        setSize(800,600);
	}
	
	private void initComponents() {
		Container contentPane = getContentPane();
		contentPane.setLayout(new GridLayout(1,2));
		
		domTree.getSelectionModel().setSelectionMode(
				TreeSelectionModel.SINGLE_TREE_SELECTION);
		//Listen for when the selection changes.
		domTree.addTreeSelectionListener(this);
		JScrollPane treeView = new JScrollPane(domTree);
		treeView.setSize(640, 480);
		
		JScrollPane attrTablePane = new JScrollPane(attrTable);
		
		contentPane.add(domTree);
		contentPane.add(attrTablePane);
	}
	
	public void valueChanged(TreeSelectionEvent e) {
    	DefaultMutableTreeNode node =
    		(DefaultMutableTreeNode) domTree.getLastSelectedPathComponent();

    	if (node == null) return;
    	if (node.isLeaf())
    		return;

    	Object nodeInfo = node.getUserObject();
  		HTMLDOMTreeNode htmlTreeNode = (HTMLDOMTreeNode) nodeInfo;
		
		AttributeSet attrs = htmlTreeNode.attr;
		
		Object[][] data = new Object[attrs.getAttributeCount()][2];
    	Enumeration en = attrs.getAttributeNames();
    	int i = 0;
    	while (en.hasMoreElements()) {
    		Object name = en.nextElement();
    		data[i][0] = name;
    		data[i][1] = attrs.getAttribute(name);
    		i++;
    	}
    	attrModel.setData(data);
    	attrTable.updateUI();
    }
	
	static final long serialVersionUID = 0x0001;
}
